package lv.solcraft.replication.server.dao;

import java.util.Date;
import java.util.List;

import lv.solcraft.replication.server.bdb.Database;
import lv.solcraft.replication.server.model.Oper;
import lv.solcraft.replication.server.model.OperId;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sleepycat.je.DatabaseException;
import com.sleepycat.persist.EntityStore;
import com.sleepycat.persist.SecondaryIndex;

@Service
public class OperDataAccess extends BaseDataAccess<OperId, Oper> {

    private OperSiteDataAccessFactory operSiteDataAccessFactory;
    private SecondaryIndex<Date, OperId, Oper> dateTimeIndex;

    @Autowired
    public OperDataAccess(EntityStore operStore, Database database) {
        super(operStore, database, OperId.class, Oper.class);
        this.operSiteDataAccessFactory = database.getOperSiteDataAccessFactory();
        try {
            this.dateTimeIndex = store.getSecondaryIndex(primary, Date.class, "dateTime");
        } catch (DatabaseException e) {
            throw new DataAccessException("Could not get opers secondary index by dateTime", e);
        }
    }

    @Override
    protected Oper afterRead(Oper entity) {
        if (entity == null)
            return null;
        entity.inject(this, operSiteDataAccessFactory);
        return entity;
    }

    public List<Oper> findBatchByDateTime(int skip, int limit) {
        return findBatch(dateTimeIndex, skip, limit);
    }
}